<template>
  <view class="container">
    <m-header>
      <view class="headerPress" @click="chooseStore">
        <image class="headerIco" src="/static/assets/icon_i_dpxx.png" mode=""></image>
        <text class="headerTxt">{{store && store.role_name || '选择门店'}}</text>
      </view>
    </m-header>
    <header-filler></header-filler>
    
    <view class="index-box" :style="'height:' + contentHeight +'px'">
      <image class="index-bg" src="/static/assets/indexbg.jpg"></image>
      <view class="head right">
        <image class="diy_navbar_des1" mode="widthFix" src="/static/assets/diy_navbar_des1.png"></image>
      </view>
      
      <view>
        <view class="head left">
          <image class="diy_navbar_des2" mode="widthFix" src="/static/assets/diy_navbar_des2.png"></image>
        </view>
        
        <view class="menus">
          <view class="item" v-for="(item, index) in menus" :key="index" :class="{'line': item.name =='line'}" @click="linkTo(item)">
            <view class="item-image" v-if="item.name != 'line'">
              <image v-if="item.name==='面包'" class="image" src="/static/category/mianbao.png"></image>
              <image v-if="item.name==='甜品'" class="image" src="/static/category/tianpin.png"></image>
              <image v-if="item.name==='乳制品'" class="image" src="/static/category/rzhipin_h.png"></image>
              <image v-if="item.name==='三明治'" class="image" src="/static/category/sanwenzhi.png"></image>
              <image v-if="item.name==='水吧'" class="image" src="/static/category/shuiba.png"></image>
              <image v-if="item.name==='烘焙机器'" class="image" src="/static/category/jiqi.png"></image>
            </view>
            <view class="item-text" v-if="item.name != 'line'">{{ item.name }}</view>
          </view>
        </view>
      </view>
    </view>
    
    
    <!-- 店铺页面组件 -->
    <!-- <Page :items="items" /> -->
    
    <float-service></float-service>
  </view>
</template>

<script>
  import { setCartTabBadge } from '@/utils/app'
  import storage from '@/utils/storage'
  import store from '@/store'
  // import * as Api from '@/api/page'
  import * as CategoryApi from '@/api/category'
  import * as UserApi from '@/api/user'
  import * as LoginApi from '@/api/login'
  import Page from '@/components/page'

  const App = getApp()

  export default {
    components: {
      Page
    },
    data() {
      return {
        // 页面参数
        options: {},
        menus: [
          {name: '面包', img: 'mianbao', category_id: 10001},
          {name: '甜品', img: 'tianpin', category_id: 10002},
          {name: '乳制品', img: 'ruzhipin', category_id: 10009},
          {name: 'line'},
          {name: '三明治', img: 'sanmingzhi', category_id: 10003},
          {name: '水吧', img: 'shuiba', category_id: 10010},
          {name: '烘焙机器', img: 'jiqi', category_id: ''},
          {name: 'line'}
        ],
        // 页面属性
        page: {},
        // 页面元素
        items: [],
        mounted: false,
        contentHeight: 800
      }
    },

    computed: {
      store() {
        return this.$store.state.app.store
      }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      // 当前页面参数
      this.options = options
      // 加载页面数据
      
      // uni.showLoading({
      //   title: '',
      // })
      const app = this
      uni.getSystemInfo({
        success(res) {
          app.contentHeight = res.windowHeight - res.statusBarHeight - 44
        }
      })
      setTimeout(() => {
        this.getPageData();
        
      }, 400)
      this.getLocation()
      
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      // 更新购物车角标
      setCartTabBadge()
      if (this.mounted) {
        this.getPageData();
      }
      
      // if (!this.store) {
      //   uni.navigateTo({
      //     url: '/pages/storelist/storelist'
      //   })
      // }
    },

    methods: {
      linkTo(item) {
        if (item.name == 'line') return
        if (item.category_id) {
          this.$store.dispatch('SetCateId', item.category_id)
          uni.switchTab({
            url: '/pages/category/index'
          })
        } else {
          uni.showToast({
            title: '敬请期待',
            icon: 'none'
          })
        }
      },
      chooseStore() {
        uni.navigateTo({
          url: '/pages/storelist/storelist'
        })
      },
      /**
       * 加载页面数据
       * @param {Object} callback
       */
      getPageData(callback) {
        const app = this
        const pageId = app.options.pageId || 0
        // Api.detail({
        //   pageId,
        //   role_id: this.store ? this.store.role_id: ''
        // })
        //   .then(result => {
        //     // 设置页面数据
        //     app.mounted = true
        //     const { data: { pageData } } = result
        //     app.page = pageData.page
        //     app.items = pageData.items
        //     // 设置顶部导航栏栏
        //     app.setPageBar();
        //   })
        //   .finally(() => callback && callback())
      },

      /**
       * 设置顶部导航栏
       */
      setPageBar() {
        const {
          page
        } = this
        // 设置页面标题
        uni.setNavigationBarTitle({
          title: page.params.title
        });
        // 设置navbar标题、颜色
        uni.setNavigationBarColor({
          frontColor: page.style.titleTextColor === 'white' ? '#ffffff' : '#000000',
          backgroundColor: page.style.titleBackgroundColor
        })
      },
      
      getLocation() {
        const stoData = storage.get('DR_SELECTED_STORE')
        uni.getLocation({
          type: 'gcj02',
          isHighAccuracy: true,
          success: (res) => {
            let location = {
              latitude: res.latitude,
              longitude: res.longitude
            }
            this.$mapSdk.reverseGeocoder({
              location,
              success: (pos) => {
                console.log(pos.result.address)
                let action = !stoData
                if (stoData) {
                  // 有缓存地区数据，但对比定位是不一样地区
                  if (pos.result.address_component.province == pos.result.address_component.city) {
                    action = stoData.region.city != pos.result.address_component.city
                  } else {
                    action = stoData.region.province != pos.result.address_component.province || stoData.region.city != pos.result.address_component.city
                  }
                }
                if (action) {
                  LoginApi.getStoreList()
                  .then(loginRes => {
                    let selectedIndex = -1
                    loginRes.data.list.map((item, i) => {
                      if (
                        pos.result.address_component.province.includes(item.region.province)
                        && item.region.city == pos.result.address_component.city
                      ) {
                        selectedIndex = i
                      }
                    })
                    let selectedItem = loginRes.data.list[selectedIndex]
                    if (selectedItem) { // 找到当地商店
                      store.dispatch('SetStore', selectedItem || {})
                    } else  { // 定位不在所有商店地区范围
                      if (!stoData) {
                        uni.navigateTo({url: '/pages/storelist/storelist'})
                      }
                    }
                  })
                }
              }
            })
          }
        })
      }

    },

    /**
     * 下拉刷新
     */
    onPullDownRefresh() {
      // 获取首页数据
      // this.getPageData(() => {
      //   uni.stopPullDownRefresh()
      // })
      uni.stopPullDownRefresh()
    },

    /**
     * 分享当前页面
     */
    onShareAppMessage() {
      const app = this
      const { page } = app
      return {
        title: page.params.share_title,
        path: "/pages/index/index?" + app.$getShareUrlParams()
      }
    },

    /**
     * 分享到朋友圈
     * 本接口为 Beta 版本，暂只在 Android 平台支持，详见分享到朋友圈 (Beta)
     * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
     */
    onShareTimeline() {
      const app = this
      const { page } = app
      return {
        title: page.params.share_title,
        path: "/pages/index/index?" + app.$getShareUrlParams()
      }
    }

  }
</script>

<style lang="scss" scoped>
@import "style.scss";
</style>
